#include "MatchProcParamCollectPanel.h"
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QVBoxLayout>
#include <QTextEdit>
#include <QRandomGenerator>
#include "../../../../models/MatchProcParamCollectData.h"
#include "../../../../models/CommonData.h"
#include "../../../../network/HttpClient.h"
#include <QComboBox>

MatchProcParamCollectPanel::MatchProcParamCollectPanel()
{

    client = new HttpClient();
    connect(client,&HttpClient::responseReceived,this,&MatchProcParamCollectPanel::onReciveResponse);
    paramKeys
        <<QString::fromStdString(BaseData<MatchProcParamCollectData>::execute(&MatchProcParamCollectData::XRayIlluminationVoltage))
        <<QString::fromStdString(BaseData<MatchProcParamCollectData>::execute(&MatchProcParamCollectData::XRayNeedleGaugeCalibrationDiameter))
        <<QString::fromStdString(BaseData<MatchProcParamCollectData>::execute(&MatchProcParamCollectData::XRayCellQrCode))
        <<QString::fromStdString(BaseData<MatchProcParamCollectData>::execute(&MatchProcParamCollectData::XRayDetectionStartTime))
        <<QString::fromStdString(BaseData<MatchProcParamCollectData>::execute(&MatchProcParamCollectData::XRayDetectionCompletionTime))
        <<QString::fromStdString(BaseData<MatchProcParamCollectData>::execute(&MatchProcParamCollectData::XRayCorner01NegativeCoveringPositive))
        <<QString::fromStdString(BaseData<MatchProcParamCollectData>::execute(&MatchProcParamCollectData::XRayCorner02NegativeCoveringPositive))
        <<QString::fromStdString(BaseData<MatchProcParamCollectData>::execute(&MatchProcParamCollectData::XRayCorner03NegativeCoveringPositive))
        <<QString::fromStdString(BaseData<MatchProcParamCollectData>::execute(&MatchProcParamCollectData::XRayCorner04NegativeCoveringPositive));

    initComponent();
}

void MatchProcParamCollectPanel::initComponent()
{
    const auto layout = new QGridLayout();
    layout->addWidget(initRequestPanel(),0,0,1,1);
    layout->addWidget(initResponsePanel(),1,0,1,1);
    setLayout(layout);
    setTitle(tr("数据采集"));
}

QWidget *MatchProcParamCollectPanel::initRequestPanel()
{
    const auto headLayout = new QGridLayout();
    const auto lbWorkStep = new QLabel(tr("工步"));
    const auto txtWorkStep = new QLineEdit();
    const auto lbLocation = new QLabel(tr("工位"));
    const auto txtLocation = new QLineEdit();
    const auto lbPcu = new QLabel(tr("产品SN"));
    const auto txtPcu = new QLineEdit();
    // const auto btnAddParam = new QPushButton(tr("添加请求参数"));
    const auto btnExecute = new QPushButton(tr("发送请求"));
    const auto lbJson = new QLabel(tr("请求体json"));
    const auto textJson = new QTextEdit();

    headLayout->addWidget(lbWorkStep,0,0,1,1);
    headLayout->addWidget(txtWorkStep,0,1,1,1);
    headLayout->addWidget(lbLocation,1,0,1,1);
    headLayout->addWidget(txtLocation,1,1,1,1);
    headLayout->addWidget(lbPcu,2,0,1,1);
    headLayout->addWidget(txtPcu,2,1,1,1);

    layout = new QGridLayout();
    btnExecute->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
    headLayout->addWidget(btnExecute,0,2,3,1);
    // headLayout->addWidget(lbJson,3,0,1,3);
    // headLayout->addWidget(textJson,4,0,1,3);
    // headLayout->addWidget(btnAddParam,3,0,1,3);
    layout->addLayout(headLayout,0,0,1,1);
    layout->addWidget(generateRequestParamList(),1,0,1,1);
    layout->addWidget(lbJson,2,0,1,1);
    layout->addWidget(textJson,3,0,1,1);

    connect(btnExecute,&QPushButton::clicked,this,&MatchProcParamCollectPanel::onSendRequest);

    requestVariableHash.insert("pcu",txtPcu);
    requestVariableHash.insert("workStep",txtWorkStep);
    requestVariableHash.insert("location",txtLocation);
    jsonHash.insert("requestBody",textJson);

    const auto widget = new QWidget();
    widget->setLayout(layout);
    return widget;
}

QWidget *MatchProcParamCollectPanel::initResponsePanel()
{
    const auto lbJson = new QLabel(tr("响应体json"));
    const auto textJson = new QTextEdit();
    const auto layout = new QGridLayout();
    layout->addWidget(lbJson,0,0,1,1);
    layout->addWidget(textJson,1,0,1,1);
    const auto widget = new QWidget();
    widget->setLayout(layout);

    jsonHash.insert("responseBody",textJson);
    return widget;
}


QWidget *MatchProcParamCollectPanel::generateRequestParamList()
{
    const auto widget = new QWidget();

    const auto lbKey = new QLabel(tr("参数编号"));
    const auto cbKey = new QComboBox();
    const auto lbValue = new QLabel(tr("参数值"));
    const auto txtValue = new QLineEdit();
    const auto lbSeq = new QLabel(tr("工步"));
    const auto txtSeq = new QLineEdit();
    const auto lbLocation = new QLabel(tr("工位"));
    const auto txtLocation = new QLineEdit();
    const auto layout = new QGridLayout();
    cbKey->addItems(paramKeys);

    layout->addWidget(lbKey,0,0,1,1);
    layout->addWidget(cbKey,0,1,1,1);
    layout->addWidget(lbValue,1,0,1,1);
    layout->addWidget(txtValue,1,1,1,1);
    layout->addWidget(lbSeq,2,0,1,1);
    layout->addWidget(txtSeq,2,1,1,1);
    layout->addWidget(lbLocation,3,0,1,1);
    layout->addWidget(txtLocation,3,1,1,1);
    widget->setLayout(layout);

    QHash<QString,QLineEdit*> paramListHash;
    paramListHash.insert("v",txtValue);
    paramListHash.insert("seq",txtSeq);
    paramListHash.insert("location",txtLocation);

    connect(cbKey,&QComboBox::currentTextChanged,this,[=](const QString& text){
        paramKey=text;
        paramListWithKeyHash.insert(paramKey,paramListHash);
    });

    // widget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
    return widget;
}

void MatchProcParamCollectPanel::onSendRequest()
{
    int randomNumber = QRandomGenerator::global()->bounded(10000,100000);
    QString dateTime = QDateTime::currentDateTime().toString("yyyyMMddhhmmssSSS");
    QString transIdStr = QString("%1%2").arg(dateTime).arg(randomNumber);
    QString dateTimeStr = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");

    // QString workStep = requestVariableHash["workStep"]->text();
    QString location = requestVariableHash["location"]->text();
    QString pcu = requestVariableHash["pcu"]->text();

    QString paramListKey = paramKey;
    QString paramListValue = paramListWithKeyHash[paramKey]["v"]->text();
    QString paramListSeq = paramListWithKeyHash[paramKey]["seq"]->text();
    QString paramListLocation = paramListWithKeyHash[paramKey]["location"]->text();


    BaseData<CommonData>::execute(&CommonData::setEventTime,dateTimeStr.toStdString());
    BaseData<CommonData>::execute(&CommonData::setTransId,transIdStr.toStdString());

    QJsonObject json;
    json["factoryNo"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getFactoryNo));
    json["transId"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getTransId));
    json["eventTime"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getEventTime));
    json["eventUser"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getEventUser));
    json["machineNo"] = QString::fromStdString(BaseData<CommonData>::execute(&CommonData::getMachineNo));

    QJsonArray paramInfoJsonArray;
    QJsonArray paramListJsonArray;

    std::list<ParamList> paramList;
    paramList.push_back({
        paramListKey.toStdString(),
        paramListValue.toStdString(),
        paramListSeq.toStdString(),
        paramListLocation.toStdString()
    });

    std::list<ParamInfo> paramInfo;
    paramInfo.push_back({
        pcu.toStdString(),
        paramList
    });

    // json["workStep"] = workStep;
    json["location"] = location;

    for(const auto& item:paramInfo)
    {
        QJsonObject paramInfoObject;
        paramInfoObject["pcu"] = QString::fromStdString(item.pcu);

        for(const auto& param:item.paramList)
        {
            QJsonObject paramListObject;
            paramListObject["k"] = QString::fromStdString(param.key);
            paramListObject["v"] = QString::fromStdString(param.value);
            paramListObject["seq"] = QString::fromStdString(param.seq);
            paramListObject["location"] = QString::fromStdString(param.location);
            paramListJsonArray.append(paramListObject);
        }
        paramInfoObject["paramList"] = paramListJsonArray;
        paramInfoJsonArray.append(paramInfoObject);
    }
    json["paramInfo"] = paramInfoJsonArray;

    std::string fullUrl = BaseData<CommonData>::execute(&CommonData::setApiUrl,"/MachProcParamCollect");
    jsonHash["requestBody"]->setPlainText(QJsonDocument(json).toJson());

    qDebug()<<"[MachProcParamCollect] request:"<<json;
    qDebug()<<"[MachProcParamCollect] url:" <<fullUrl;


    client->PostAysnc(QString::fromStdString(fullUrl),json);

}

void MatchProcParamCollectPanel::onReciveResponse(const QByteArray &json)
{
    qDebug()<<"[MachProcParamCollect] response:"<<json;
    QJsonDocument doc = QJsonDocument::fromJson(json);
    jsonHash["responseBody"]->setPlainText(doc.toJson());
    if(!doc.isNull())
    {
        QJsonObject obj = doc.object();
        int resultCode = obj["resultCode"].toInt();
        if(resultCode == 0)
        {

        }


    }
}
